package conf

import (
	"math/rand"
	"path/filepath"
	"talent.com/agency_im/conf/g"
	"talent.com/agency_im/conf/internal"
	"talent.com/server/durotar.git/log"
	"talent.com/server/durotar.git/tools"
	"talent.com/server/durotar.git/tools/database"
	"talent.com/server/durotar.git/tools/fs"
	"talent.com/server/durotar.git/tools/tz"
	"time"
)

var loadFuncs = map[string]func(string, bool){
	"server.toml": internal.ReloadServerConfig,
	"biz.toml":    internal.ReloadBizConfig,
}

var (
	configBasePath = tools.GetConfigDir()
	lastModifyInfo = make(map[string]int64, 2)

	ServerConfig = internal.GetServerConfig
	BizConfig    = internal.GetBizConfig
)

func stopInitIfError(err error) {
	if err != nil {
		log.Fatal("stop init for %v", err.Error())
	}
}

func InitConfig() {
	var (
		err  error
		path string
	)
	rand.Seed(time.Now().Unix())
	for f, fn := range loadFuncs {
		path = filepath.Join(configBasePath, f)
		lastModifyInfo[f], err = fs.GetLastModifyTime(path)
		stopInitIfError(err)
		fn(path, false)
	}

	sc := ServerConfig()
	db := sc.DB
	redisConfig := sc.Redis

	g.ORM = database.NewMysqlConn(db.Host, db.IsDebug)
	g.RedisPool = database.NewRedisPool(redisConfig.Host, redisConfig.Password, redisConfig.Index)

	tz.Schedule(reloadConfig, g.ReloadCycle, g.GameCloseChan)
}

func reloadConfig() {
	var (
		path string
		err  error
		ts   int64
	)
	for f, fn := range loadFuncs {
		path = filepath.Join(configBasePath, f)
		ts, err = fs.GetLastModifyTime(path)
		if err != nil {
			log.Error("can't reload %v, please check!!!!", path)
			continue
		}
		if lastModifyInfo[f] != ts {
			fn(path, true)
			lastModifyInfo[f] = ts
			log.Info("config %v reloaded", f)
		}
	}
}

func CloseAll() {
	_ = g.ORM.Close()
	g.RedisPool.Close()
	close(g.GameCloseChan)
}
